<template xmlns="http://www.w3.org/1999/html">

  <a-modal
    title="新增退货单"
    :visible="visible"
    width=70%
    @cancel="handleCancel"
  >

    <div class="firstLine">
      <!--      基本信息-->
      <a-card style="margin-bottom: 10px">
        <div class="essential" style="border-bottom: 1px dashed #eae2e2;">
          <div class="essential_text">基本信息</div>
          <a-form :form="form">
            <a-row :gutter="24">
              <!--            门店名称-->
              <a-col :md="22" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="门店名称"
                >
                  <!--                <app-stores ref="appStores" placeholder="请选择门店" @change="inputChange"-->
                  <!--                            v-decorator="['terminalCode',{rules: [{ required: true, message: '门店名称不能为空' }]}]">-->
                  <!--                </app-stores>-->
                  <TerminalChose width=75% @inputs="getinputsvalue" v-bind="configs" v-on="$listeners"
                                 v-model="terminalCodes"
                                 :disabled="relevals" @change="inputsome"></TerminalChose>
                </a-form-item>
                <!--      wheel默认使用v-modal使用decorater会产生预警冲突        v-decorator="['terminalCode',{rules: [{ required: true, message: '门店名称不能为空' }]}]"-->
              </a-col>
              <!--            是否关联-->
              <a-col :md="22" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="关联订单">
                  <a-radio-group :disabled="relevals"
                                 v-decorator="['relevance', {initialValue:'2',rules: [{ required: true, message: '请选择需要关联的订单' }]}]"
                                 @change="wheatherContact">
                    <a-radio value="2">
                      不关联
                    </a-radio>
                    <a-radio value="1">
                      关联
                    </a-radio>
                  </a-radio-group>
                  <a-input-search placeholder="请输入" v-if="!productAd"
                                  readOnly v-decorator="['orderCode']"
                                  @search="searchOrder"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
      <!--      订货信息-->
      <a-card title="退货清单" style="width: 100%;margin-bottom:10px" v-if="productAd">
        <div class="essential">
          <a-table :scroll="{x: 'max-content'}" :columns="columns" :data-source="dataSource" :pagination="false">
            <!--          退货数量-->
            <template slot="itemNum" slot-scope="text,record">
              <a-input type="number" style="width: 80px" v-model='text' :min="0"
                       placeholder="请输入" @change="onCellChange(record, 'itemNum',text,'up')"/>
            </template>
            <!--          退货价格-->
            <template slot="price" slot-scope="text,record">
              <a-input type="number" style="width: 80px" v-model='text' :min="0"
                       placeholder="请输入" @change="onCellChange(record,'price',text,'up')"/>
            </template>
            <!--            价格小计-->
            <template slot="returnAmount" slot-scope="text,record">
              <span>{{ record.itemNum == null ? '' : record.price * record.itemNum | moneyTwoPoint }}元</span>
            </template>
            <template slot="remarks" slot-scope="text,record">
              <a-input type="text-area" style="width: 120px" v-model='text'
                       placeholder="请输入" @change="onCellChange(record,'remarks',text)"/>
            </template>
            <template slot="action" slot-scope="text, record">
              <a @click="handleDeleteSelected(record)">删除</a>
            </template>

          </a-table>
          <div style="margin: 8px 2px;color: #2276d2"><a @click="handleAddgoods('Origin')" :disabled="relevals">+
            添加商品</a>
          </div>
        </div>
        <!--      添加赠品-->
        <div class="essential">
          <!--        <div class="essential_text">订货信息</div>-->
          <a-table :scroll="{x: 'max-content'}" :columns="columns2" :data-source="dataSource2" :pagination="false">
            <!--          退货数量-->
            <template slot="itemNum" slot-scope="text,record">
              <a-input type="number" style="width: 80px" v-model='text' :min="0"
                       placeholder="请输入" @change="onCellChange2(record, 'itemNum',text)"/>
            </template>
            <template slot="price" slot-scope="text,record">
              <span type="number" style="width: 80px" v-model="text"></span>
            </template>
            <template slot="remarks" slot-scope="text,record">
              <a-input style="width: 120px" v-model='text'
                       placeholder="请输入" @change="onCellChange2(record, 'remarks',text)"/>
            </template>
            <template slot="action" slot-scope="text, record">
              <a @click="handleDeleteSelected(record,'promotion')">删除</a>
            </template>
          </a-table>
          <div style="margin: 8px 2px;color: #2276d2"><a @click="handleAddgoods('promotion')" :disabled="relevals">+
            添加赠品</a></div>
        </div>
        <div class="Poolbalance">
          <div class="Orderitems">
            <div class="OrderItem"><span style="line-height: 32px;margin-right:5px">退款总金额:</span><span
              style="color: firebrick;font-size: 16px">{{ allMoney | moneyTwoPoint }}</span></div>
            <div class="OrderItem">
              <span style="margin-right: 5px">运费:</span>
              <a-input type="Number" min="0" v-model="carriage" style="width: 70px;height: 32px" label="运费"
                       :disabled="relevals"></a-input>
            </div>
            <!--          <div class="OrderItem">应付金额:</div>-->
          </div>
        </div>
      </a-card>
      <!--      关联 退货订单-->
      <a-card title="退货清单" style="width: 100%;margin-bottom:10px" v-if="!productAd">
        <div class="essential">
          <a-table :scroll="{x: 'max-content'}" :columns="columns3" :data-source="dataSource3" :pagination="false">
          </a-table>
        </div>
        <!--      添加赠品-->
        <div class="essential">
          <!--        <div class="essential_text">订货信息</div>-->
          <a-table :scroll="{x: 'max-content'}" :columns="columns4" :data-source="dataSource4"
                   :pagination="false"></a-table>
          <div class="Poolbalance" style="margin-top: 15px">
            <div class="Orderitems">
              <div class="OrderItem"><span style="line-height: 32px;margin-right:5px">退款总金额:</span><span
                style="color: firebrick;font-size: 16px">{{ allMoney |moneyTwoPoint }}</span></div>
              <div class="OrderItem">
                <span style="margin-right: 5px">运费:</span>
                <a-input type="Number" min="0" v-model="carriage" style="width: 70px;height: 32px"
                         label="运费"></a-input>
              </div>
              <!--          <div class="OrderItem">应付金额:</div>-->
            </div>
          </div>
        </div>
      </a-card>
      <!--其他信息区域-->
      <a-card style="margin-top: 10px">
        <div class="essential">
          <div class="essential_text">其他信息</div>
          <a-form-item :labelCol="{
                     xs: { span: 24 },
                     sm: { span: 2 }
                     }"
                       :wrapperCol="{
                     xs: { span: 24 },
                     sm: { span: 24 }
                     }" label="">
            <a-textarea placeholder="请输入备注" style="min-height: 60px" v-model="remarks" auto-size :disabled="relevals"/>
          </a-form-item>
        </div>
      </a-card>
    </div>
    <!--    添加商品-->
    <productcontact ref="productModal" @productcontact="productcontacts"></productcontact>
    <!--    添加订单-->
    <terminalOrderlist ref="orderList" @productcon="searchOrderCode"></terminalOrderlist>

    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleToSendNew" type="primary" v-if="sureTo" :disabled="sendReturn">
        <a-spin :spinning="sendReturn">确认</a-spin>
      </a-button>
      <a-button @click="choseToCheck('1')" type="primary" v-if="checksNow">通过</a-button>
      <a-button @click="choseToCheck('2')" type="primary" v-if="checksNow">驳回</a-button>
    </template>

  </a-modal>

</template>

<script>
import TerminalChose from '@/components/cn-components/TerminalChose'
import terminalOrderlist from '@/views/mdm/return-goods/modules/TerminalOrderlist'
import productcontact from '@/components/cn-components/ProductContact'
import { getAction, postAction } from '@/api/manage'
import UploadImage from '@/components/upload-image/UploadImage'


export default {
  name: 'AddReturnModal',
  components: { UploadImage, productcontact, terminalOrderlist, TerminalChose },

  data() {
    return {
      sendReturn: false,
      terminalCodes: '',
      sureTo: true,
      modals: {},
      relevals: false,
      checksNow: false,
      inputsValue: [],
      settings: {
        name: '门店',
        displayKey: 'terminalName',
        returnKeys: ['id', 'terminalCode'],
        listUrl: '/cnTerminalController/custFindTerminalList',
        queryParamCode: 'terminalName',
        queryParamText: '门店名称',
        columns: [
          { title: '门店编号', dataIndex: 'terminalCode', align: 'center', width: '50%', widthRight: '70%' },
          { title: '门店名称', dataIndex: 'terminalName', align: 'center', width: '50%', widthRight: '70%' }
        ]
      },
      // appStores初始化
      terminals: '',

      remarks: '',
      allMoney: 0,
      nums: 0,
      productAd: true,
      carriage: 0,
      // 收货地址列表
      selectOptions: [],
      visible: false,
      dataSource: [],
      dataSource2: [],
      dataSource3: [],
      dataSource4: [],
      form: this.$form.createForm(this),
      // label框
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      // 文本框
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      modal: {},
      queryParam: {},
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'saleUnit'
          // customRender: function(text) {
          //   if (text == 'box') {
          //     return '箱'
          //   } else if (text == 'pot') {
          //     return '罐'
          //   } else if (text == 'bottle') {
          //     return '瓶'
          //   } else {
          //     return text
          //   }
          // }
        },
        {
          title: '标准订货价',
          align: 'center',
          dataIndex: 'custPrice'
        },
        {
          title: '退货数量',
          align: 'center',
          dataIndex: 'itemNum',
          scopedSlots: { customRender: 'itemNum' }
        },
        {
          title: '退货价',
          align: 'center',
          dataIndex: 'price',
          scopedSlots: { customRender: 'price' }
        },
        {
          title: '退货金额小计',
          align: 'center',
          dataIndex: 'returnAmount',
          scopedSlots: { customRender: 'returnAmount' }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          width: '200',
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns2: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '赠品编号',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '赠品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'saleUnit',
          customRender: function(text) {
            if (text == 'box') {
              return '箱'
            } else if (text == 'pot') {
              return '罐'
            } else if (text == 'bottle') {
              return '瓶'
            } else {
              return text
            }
          }
        },
        {
          title: '标准订货价',
          align: 'center',
          dataIndex: 'custPrice'
        },
        {
          title: '退货数量',
          align: 'center',
          dataIndex: 'itemNum',
          scopedSlots: { customRender: 'itemNum' }
        },
        {
          title: '退货价',
          align: 'center',
          dataIndex: 'price',
          // scopedSlots: { customRender: 'price' }
          customRender: function() {
            return 0
          }
        },
        {
          title: '退货金额小计',
          align: 'center',
          dataIndex: 'returnAmount',
          // scopedSlots: { customRender: 'returnAmount' }
          customRender: function() {
            return 0
          }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          width: '200',
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns3: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'saleUnit',
          customRender: function(text) {
            if (text == 'box') {
              return '箱'
            } else if (text == 'pot') {
              return '罐'
            } else if (text == 'bottle') {
              return '瓶'
            } else {
              return text
            }
          }
        },
        {
          title: '标准订货价',
          align: 'center',
          dataIndex: 'oldPrice'
        },
        {
          title: '退货数量',
          align: 'center',
          dataIndex: 'itemNum',
          scopedSlots: { customRender: 'itemNum' }
        },
        {
          title: '退货价',
          align: 'center',
          dataIndex: 'price',
          // scopedSlots: { customRender: 'price' }
          customRender: function() {
            return 0
          }
        },
        {
          title: '退货金额小计',
          align: 'center',
          dataIndex: 'returnAmount'
          // scopedSlots: { customRender: 'returnAmount' }
          // customRender: function() {
          //   return 0
          // }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          width: '200',
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns4: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '赠品编号',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '赠品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'saleUnit',
          customRender: function(text) {
            if (text == 'box') {
              return '箱'
            } else if (text == 'pot') {
              return '罐'
            } else if (text == 'bottle') {
              return '瓶'
            } else {
              return text
            }
          }
        },
        {
          title: '标准订货价',
          align: 'center',
          dataIndex: 'oldPrice'
        },
        {
          title: '退货数量',
          align: 'center',
          dataIndex: 'itemNum',
          scopedSlots: { customRender: 'itemNum' }
        },
        {
          title: '退货价',
          align: 'center',
          dataIndex: 'price',
          // scopedSlots: { customRender: 'price' }
          customRender: function() {
            return 0
          }
        },
        {
          title: '退货金额小计',
          align: 'center',
          dataIndex: 'returnAmount'
          // scopedSlots: { customRender: 'returnAmount' }
          // customRender: function() {
          //   return 0
          // }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          width: '200',
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        storelist: window._CONFIG['domianURL'] + '/cnTerminalController/custTerminalAllList',
        saveOrder: window._CONFIG['domianURL'] + '/order/cnOrderReturnItemController/saveReturn',
        returnList: window._CONFIG['domianURL'] + '/cnOrderController/getCnOrderByIdOrOrderCode',
        checkReturnOrder: window._CONFIG['domianURL'] + '/order/cnOrderReturnItemController/checkReturn'
      },
      validatorRules: {
        relevance: { rules: [{ required: true, message: '' }] }
      }
    }
  },
  computed: {
    configs() {
      return Object.assign({ value: this.value }, this.settings, this.$attrs)
    }
  },
  methods: {
    getinputsvalue(value) {
      console.log(value)
      this.terminalName = value[0].terminalName
    },
    inputsome(value) {
      if (value == '' || value == undefined) {
        this.$message.error('门店已置空')
        return
      }
      this.terminals = value
    },
    add() {
      this.edit()
    },
    edit(record, status, logos) {
      this.form.resetFields()
      this.visible = true
      this.relevals = false
      this.sureTo = true
      this.modals = record
      this.productAd = true
      this.checksNow = false
      this.terminalCodes = ''
      if (status == 'details') {
        this.sureTo = false
        this.relevals = true
        let products = []
        let gifts = []
        // 退货单商品列表
        record.list.forEach(item => {
          if (item.itemType == '1') {
            products.push(item)
          } else {
            gifts.push(item)
          }
        })
        if (record.relevance == 2) {
          this.productAd = true
          this.dataSource = products
          this.dataSource2 = gifts
        } else {
          this.productAd = false
          this.dataSource3 = products
          this.dataSource4 = gifts
        }
        this.allMoney = this.modals.returnAmount
        this.carriage = this.modals.carriage
        this.remarks = this.modals.remarks
        this.terminalCodes = this.modals.terminalName
        this.$nextTick(() => {
          this.form.setFieldsValue({
            relevance: this.modals.relevance,
            orderCode: this.modals.orderCode
          })
        })
      }
      if (logos == 'checks') {
        this.checksNow = true
      }
      // this.$nextTick(function(){
      //   this.form.setFieldsValue({
      //     terminalCode:'1'
      //   })
      // })
      // this.form.getFieldValue('terminalCode')
    },
    // 添加商品点击事件
    handleAddgoods(value) {
      this.$refs.productModal.visitproducts(value)
    },
    productcontacts(value, type) {
      let newValue = JSON.parse(JSON.stringify(value))
      newValue.forEach(item => {
        item.itemNum = 1
        item.price = item.custPrice
      })
      if (type == 'Origin') {
        this.dataSource = JSON.parse(JSON.stringify(newValue))
        let a = 0
        this.dataSource.forEach(item => {
          a = a + (item.custPrice - 0) * (item.itemNum - 0)
        })
        this.allMoney = a
      } else {
        this.dataSource2 = JSON.parse(JSON.stringify(newValue))
      }
    },
    // 表格行内订单数量
    onCellChange(cord, option, nums) {
      let dataSource = []
      dataSource = [...this.dataSource]
      let target = dataSource.find(item => item.productCode === cord.productCode)
      if (target) {
        target[option] = nums
        target.returnAmount = target.price * target.itemNum
      }
      this.dataSource = dataSource
      let a = 0
      this.dataSource.forEach(item => {
        if (item.returnAmount) {
          a += item.returnAmount
        }
      })
      this.allMoney = a
    },
    onCellChange2(cord, option, nums) {
      let dataSource = [...this.dataSource2]
      console.log(dataSource)
      let target = dataSource.find(item => item.productCode === cord.productCode)
      if (target) {
        target[option] = nums
      }
      this.dataSource2 = dataSource
    },
    // 点击删除事件
    handleDeleteSelected(cord, dataIndex) {
      if (dataIndex == 'promotion') {
        const dataSource = [...this.dataSource2]
        this.dataSource2 = dataSource.filter(item => item.id !== cord.id)
      } else {
        const dataSource = [...this.dataSource]
        this.dataSource = dataSource.filter(item => item.id !== cord.id)
      }
    },
    // 是否关联切换
    wheatherContact(values) {
      this.form.resetFields(['relevance', 'orderCode'])
      this.allMoney = 0
      this.sendMoney = 0
      this.remarks = ''
      this.dataSource = []
      this.dataSource2 = []
      let type = values.target.value
      if (type == '2') {
        this.productAd = true
      } else {
        this.productAd = false
      }
    },
    searchOrder() {
      if (this.terminals == '') {
        this.$message.info('门店不能为空')
        return
      }
      this.$refs.orderList.visitproducts(this.terminals)
    },
    // 关联商品详情
    searchOrderCode(value) {
      this.form.setFieldsValue({
        orderCode: value[0]
      })
      getAction(this.url.returnList, { orderCode: value[0] }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        this.dataSource3 = []
        this.dataSource4 = []
        let result = res.result.items
        // this.terminalName = res.result.terminalName
        result.forEach(item => {
          if (item.itemType == '1') {
            let a = 0
            this.dataSource3.push(item)
            this.dataSource3.forEach(item => {
              item.returnAmount = item.itemNum * item.oldPrice
              a += item.returnAmount
            })
            this.allMoney = a
          } else {
            this.dataSource4.push(item)
          }
        })
      })
    },
    // inputChange(value) {
    //
    //   console.log(this.stores)
    // },
    // 周周期响应确认提交事件
    handleToSendNew() {
      this.form.validateFields((err, values) => {
        this.sendReturn = true
        if (err) {
          this.$message.error('请检查必填项')
          return
        }
        this.dataSource.forEach(item => {
          item.itemType = 1
        })
        this.dataSource2.forEach(item => {
          item.itemType = 2
        })
        // 拼接数据
        let formData = Object.assign({}, values)
        let Array1 = []
        let Array2 = []
        if (values.relevance == '2') {
          Array1 = this.dataSource
          Array2 = this.dataSource2
        } else {
          Array1 = this.dataSource3
          Array2 = this.dataSource4
        }
        formData.list = [...Array1, ...Array2]
        formData.carriage = this.carriage
        formData.remarks = this.remarks
        formData.chargeback = 2
        formData.returnAmount = this.allMoney
        formData.terminalCode = this.terminals
        formData.terminalName = this.terminalName
        postAction(this.url.saveOrder, formData).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            this.sendReturn = false
            return
          }
          this.sendReturn = false
          this.handleCancel()
          this.$emit('ok')
        })
      })
    },
// 确认提交事件
    handleOk() {
      this.form.validateFields((err, values) => {
        if (err) {
          this.$message.error('请检查必填项')
          return
        }
        this.dataSource.forEach(item => {
          item.itemType = 1
        })
        this.dataSource2.forEach(item => {
          item.itemType = 2
        })
        // 拼接数据
        let formData = Object.assign({}, values)
        let Array1 = []
        let Array2 = []
        if (values.relevance == '2') {
          Array1 = this.dataSource
          Array2 = this.dataSource2
        } else {
          Array1 = this.dataSource3
          Array2 = this.dataSource4
        }
        formData.list = [...Array1, ...Array2]
        formData.carriage = this.carriage
        formData.remarks = this.remarks
        formData.chargeback = 2
        formData.returnAmount = this.allMoney
        formData.terminalCode = this.terminals
        formData.terminalName = this.terminalName
        postAction(this.url.saveOrder, formData).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          this.$emit('ok')
        })

      })
    },
    choseToCheck(status) {
      const cord = this.modals
      let params = {
        id: cord.id,
        bpmStatus: status,
        orderStatus: cord.orderStatus
      }
      postAction(this.url.checkReturnOrder, { ...params }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.handleCancel()
        } else {
          this.$message.warning(res.message)
          this.handleCancel()
        }
      })
    },
    handleCancel() {
      this.terminals = ''
      this.terminalName = ''
      this.remarks = ''
      this.carriage = 0
      this.allMoney = 0
      this.dataSource = []
      this.dataSource2 = []
      this.dataSource3 = []
      this.dataSource4 = []
      this.visible = false
    }
  }
}
</script>

<style scoped>
.firstLine {
  padding: 0 3%;
}

.essential_text {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 8px;
}

.essential {
  padding: 10px 0;
  margin-bottom: 15px;
}

.Poolbalance {
  border-bottom: 1px dashed #f0f0f0;
  padding-bottom: 15px;
}

.Orderitems {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.OrderItem {
  margin-right: 50px;
  font-size: 14px;
}
</style>